use crate::entities::user::{self, Entity as UserEntity};
use dotenvy;
use sea_orm::{
    ActiveValue::Set, ConnectionTrait, Database, DatabaseConnection, DbErr, EntityTrait,
    PaginatorTrait,
};
use std::{env, path::PathBuf};

fn load_env() -> Result<(), Box<dyn std::error::Error>> {
    let env_path = if cfg!(debug_assertions) {
        // 开发环境：子模块路径
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(".env")
    } else {
        // 生产环境：当前工作目录
        env::current_dir()?.join(".env")
    };

    // 检查文件是否存在
    if !env_path.exists() {
        let env_type = if cfg!(debug_assertions) { "submodule" } else { "current" };
        eprintln!("Warning: .env not found in {} dir: {:?}", env_type, env_path);
    } else {
        dotenvy::from_path(env_path)?;
    }

    Ok(())
}

pub async fn establish_connection() -> Result<DatabaseConnection, DbErr> {
    // 如果 load_env 失败，直接终止
    load_env().map_err(|e| DbErr::Custom(format!("Env load failed: {}", e)))?;

    // 只有成功才会继续
    let database_url = env::var("DATABASE_URL")
        .map_err(|e| DbErr::Custom(format!("DATABASE_URL not set: {}", e)))?;

    let db = Database::connect(database_url).await?;

    // 建表和初始化数据
    let _ = db.execute_unprepared(
        "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)"
    ).await?;

    if UserEntity::find().count(&db).await? == 0 {
        UserEntity::insert_many(vec![
            user::ActiveModel { name: Set("Alice".to_owned()), ..Default::default() },
            user::ActiveModel { name: Set("Bob".to_owned()), ..Default::default() },
        ]).exec(&db).await?;
    }

    Ok(db)
}